package com.junjie.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * /**
 * cookie工具，封装了cookie的添加、
 * 查询、删除操作。
 * @author teacher
 *
 */
public class CookieUtil {
	public static String path="/MyDangDang";//cookie的默认保存路径
	public static int age=365*24*3600;//cookie的有效时间
	
	/**
	 * 添加cookie
	 */
	public static void addCookie(String name,String value,HttpServletResponse response,int maxAge) throws UnsupportedEncodingException{
		Cookie cookie = new Cookie(name,URLEncoder.encode(value,"utf-8"));
		cookie.setMaxAge(maxAge);
		cookie.setPath(path);
		response.addCookie(cookie);
	}

	/**
	 * 添加cookie(方法重载)
	 */
	public static void addCookie(String name,String value,HttpServletResponse response) throws UnsupportedEncodingException{
		addCookie(name,value,response,age);
	}
	/**
	 * 依据cookie的名字返回其值，
	 * 如果找不到，则返回null。
	 */
	public static String findCookie(String name,HttpServletRequest request) throws UnsupportedEncodingException{
		String value = null;
		Cookie[] cookies = request.getCookies();
		if(cookies != null){
			for(int i=0;i<cookies.length;i++){
				Cookie cookie = cookies[i];
				if(cookie.getName().equals(name)){
					value = URLDecoder.decode(cookie.getValue(),"utf-8");
				}
			}
		}
		return value;
	}
	
	/**
	 * 删除cookie
	 */
	public static void deleteCookie(String name,HttpServletResponse response){
		Cookie cookie = new Cookie(name,"");
		cookie.setMaxAge(0);
		cookie.setPath(path);
		response.addCookie(cookie);
	}
}
